package com.yun.apply.system.service.impl;

import com.yun.apply.system.domain.SysUserRole;
import com.yun.apply.system.mapper.SysUserMapper;
import com.yun.apply.system.mapper.SysUserRoleMapper;
import com.yun.apply.system.service.ISysUserService;
import com.yun.common.core.domain.SysUser;
import com.yun.common.exception.CustomException;
import com.yun.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser selectUserByUserName(String username) {
        return userMapper.selectUserByUserName(username);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (user.getUserId() != null && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int insertUser(SysUser user) {
        this.checkUser(user, true);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int rows = userMapper.insert(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int updateUser(SysUser user) {
        this.checkUser(user, false);
        Long userId = user.getUserId();
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        return userMapper.updateById(user);
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int resetPwd(SysUser user) {
        SysUser exitUser = userMapper.selectUserById(user.getUserId());
        if (exitUser == null) {
            throw new CustomException("用户不存在");
        }
        exitUser.setPassword(user.getPassword());
        return userMapper.updateById(exitUser);
    }

    /**
     * 删除
     * @param userIds
     * @return
     */
    @Override
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

    @Override
    public int updateUserStatus(SysUser user) {
        SysUser exitUser = userMapper.selectUserById(user.getUserId());
        if (exitUser == null) {
            throw new CustomException("用户不存在");
        }
        exitUser.setEnable(user.getEnable());
        return userMapper.updateById(exitUser);
    }

    /**
     * 新增角色
     * @param user
     */
    private void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (roles != null)
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }


    /**
     * 检查用户
     * @param user
     */
    private void checkUser(SysUser user, boolean add) {
        String msg = add ? "新增用户" : "修改用户";
        Long userId = user.getUserId() == null ? -1L : user.getUserId();
        // 检验用户名
        int count = userMapper.checkUserNameUnique(user.getUsername(), userId);
        if (count > 0) {
            throw new CustomException(msg + "'" + user.getUsername() + "'失败，登录账号已存在");
        }
        // 效验手机号
        count = userMapper.checkPhoneUnique(user.getPhoneNumber(), userId);
        if (count > 0) {
            throw new CustomException(msg + "'" + user.getUsername() + "'失败，手机号码已存在");
        }
        // 效验邮箱
        count = userMapper.checkEmailUnique(user.getEmail(), userId);
        if (count > 0) {
            throw new CustomException(msg + "'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
    }

}
